#!/usr/bin/env python
# _*_coding:utf-8 _*_
__author__ = "Gao"
"""
判断是否接到炸弹:
1. 炸弹中心点的y坐标大于挡板的y坐标
2. 炸弹中心点的x坐标在挡板x轴区间内
"""


import sys, random, time, pygame

from pygame.locals import *

def print_text(font,x,y,text,color=(255,255,255)):
    imgText = font.render(text,True,color)
    screen.blit(imgText,(x,y))

pygame.init()

screen = pygame.display.set_mode((600,500))

font1 = pygame.font.Font(None,24)
pygame.mouse.set_visible(False)    # 隐藏鼠标

white = 255,255,255
red = 220,50,50
yellow = 230,230,50
black = 0,0,0

lives = 3
score = 0
game_over = True

mouse_x = 0
mouse_y = 0

pos_x = 300    # 挡板的x坐标
pos_y = 460    # 挡板的y坐标

bomb_x = random.randint(0,500)
bomb_y = -50    # 炸弹起始y坐标

vel_y = 0.2    # 炸弹下落速度

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x,mouse_y = event.pos    # 获取鼠标移动后的坐标
            move_x,move_y = event.rel    # 获取鼠标的位移
        elif event.type == MOUSEBUTTONUP:
            # 点击鼠标，初始化游戏
            if game_over:
                game_over = False
                lives = 3
                score = 0

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()

    screen.fill((0,0,100))
    if game_over:    # 当游戏结束时，打印提示信息
        print_text(font1,100,200,'<click to play')
    else:
        # 移动炸弹
        bomb_y += vel_y

        if bomb_y > 500:    # 没有接到炸弹
            bomb_x = random.randint(0,500)
            bomb_y = -50
            lives -= 1
            if lives == 0:
                game_over = True
        elif bomb_y > pos_y:    # 判断挡板是否接到炸弹
            if bomb_x > pos_x and bomb_x < pos_x + 120:    # 炸弹中心点必须在挡板上
                score += 10
                bomb_x = random.randint(0,500)
                bomb_y = -50

        pygame.draw.circle(screen,black,(bomb_x-4,int(bomb_y)-4),30,0)    # 炸弹影子
        pygame.draw.circle(screen,yellow,(bomb_x,int(bomb_y)),30,0)

        # 移动挡板
        pos_x = mouse_x
        if pos_x < 0:
            pos_x = 0
        elif pos_x > 500:
            pos_x = 500
        pygame.draw.rect(screen,black,(pos_x-4,pos_y-4,120,40),0)    # 挡板阴影
        pygame.draw.rect(screen,red,(pos_x,pos_y,120,40),0)

    print_text(font1,0,0,'lives:'+str(lives))
    print_text(font1,500,0,'score:'+str(score))
    pygame.display.update()